import React, { Component } from 'react'
import axios from 'axios';
import CatsList from '../CatsList'
import './index.css'

export default class List extends Component {
  state = {
    url: 'http://5c92dbfae7b1a00014078e61.mockapi.io/owners',
    list: []
  }
  componentDidMount () {
    const { url } = this.state;
    axios.get(url).then(res => {
      let ownersList = [...res.data];
      let genders = new Set(ownersList.map(owner => owner.gender));
      genders = [...genders];

      if (genders.length) {
        let list = [];
        genders.forEach((gender, i) => {
          let tempList = ownersList.filter(owner => owner.gender === gender);
          let petsList = [];
          let catsList = [];

          if (tempList.length) {
            tempList.forEach(owner => {
              if (owner.pets && owner.pets.length) {
                petsList.push(owner.pets)
              }
            });
          }
          if (petsList.length) {
            catsList = petsList.flat().filter(pet => pet.type === 'Cat');
            catsList.sort((itemN, itemM) => itemN.name > itemM.name ? 1 : -1);
          }
          list[i] = {
            gender,
            catsList
          }
        })
        this.setState({ list });
      }

    })
  }
  render () {
    const { list } = this.state;
    return (
      <div className="list">
        {
          list.map((item, index) => {
            return <div key={index} className="owners-list">
              <div>{item.gender}</div>
              <CatsList catsList={item.catsList}></CatsList>
            </div>
          })
        }
      </div>
    )
  }
}